//
//  CLReadController.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/7/21.
//

#import "CLReadController.h"
#import "CLReadLongPressView.h"
#import "CLReadController+EffectType.h"
#import "CLReadCatalogView.h"
#import "CLReadMarkView.h"
#import "CLReadController+Operation.h"
#import "CLReadModel+Mark.h"
// MARK: Block

/// 动画完成
typedef void (^CLAnimationCompletion)(void);

@interface CLReadController ()<CLReadMenuDelegate, CLReadCatalogViewDelegate, CLReadMarkViewDelegate, CLReadContentViewDelegate>

@end

@implementation CLReadController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化书籍阅读记录
    [self updateReadRecordWithRecordModel:self.readModel.recordModel];

    // 初始化菜单
    self.readMenu = [[CLReadMenu alloc]initWithVc:self delegate:self];

    // 背景颜色
    self.view.backgroundColor = CLReadConfigure.sharedInstance.bgColor;

    // 初始化控制器
    [self creatPageController:[self getCurrentReadViewController:YES]];

    // 监控阅读长按视图通知
    [self monitorReadLongPressView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication.sharedApplication setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication.sharedApplication setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)addSubviews {
    [super addSubviews];

    // 目录侧滑栏
    CLReadLeftView *leftView = [[CLReadLeftView alloc]init];
    self.leftView = leftView;
    leftView.catalogView.readModel = self.readModel;
    leftView.catalogView.delegate = self;
    leftView.markView.readModel = self.readModel;
    leftView.markView.delegate = self;
    leftView.hidden = YES;
    [self.view addSubview:leftView];
    leftView.frame = CGRectMake(-CL_READ_LEFT_VIEW_WIDTH, 0, CL_READ_LEFT_VIEW_WIDTH, CL_READ_LEFT_VIEW_HEIGHT);

    // 阅读视图
    CLReadContentView *contentView = [[CLReadContentView alloc]init];
    self.contentView = contentView;
    contentView.delegate = self;
    [self.view addSubview:contentView];
    contentView.frame = CGRectMake(0, 0, CL_READ_CONTENT_VIEW_WIDTH, CL_READ_CONTENT_VIEW_HEIGHT);
    
}

// MARK: 监控阅读长按视图通知

// 监控阅读长按视图通知
- (void)monitorReadLongPressView {

    if ([CLReadConfigure sharedInstance].openLongPress) {
        CL_READ_NOTIFICATION_MONITOR(self, @selector(longPressViewNotification:));
    }
}

// 处理通知
- (void)longPressViewNotification:(NSNotification *)notification {

    // 获得状态
    NSDictionary *info = notification.userInfo;

    // 隐藏菜单
    [self.readMenu showMenu:NO];

    // 解析状态
    if (info != nil && [info.allKeys containsObject:CL_READ_KEY_LONG_PRESS_VIEW]) {

        NSNumber *isOpen = info[CL_READ_KEY_LONG_PRESS_VIEW];

        self.coverController.gestureRecognizerEnabled = isOpen.boolValue;

        self.pageViewController.gestureRecognizerEnabled = isOpen.boolValue;

        self.readMenu.singleTap.enabled = isOpen.boolValue;
    }
}


// MARK: DZMReadCatalogViewDelegate

/// 章节目录选中章节
- (void)catalogViewClickChapterWithCatalogView:(CLReadCatalogView *)catalogView chapterListModel:(CLReadChapterListModel *)chapterListModel {

    [self showLeftView:NO];

    [self.contentView showCover:NO];

    if ([self.readModel.recordModel.chapterModel.chapterid isEqualToString: chapterListModel.chapterid]) { return; }

    [self goToChapter:chapterListModel.chapterid toPage:0];
}

// MARK: DZMReadMarkViewDelegate

/// 书签列表选中书签
- (void)markViewClickMark:(CLReadMarkView *)markView markModel:(CLReadMarkModel *)markModel {

    [self showLeftView:NO];

    [self.contentView showCover:NO];

    [self goToChapter:markModel.chapterid location:markModel.location];
}


// MARK: DZMReadContentViewDelegate

/// 点击遮罩
- (void)contentViewClickCover:(CLReadContentView *)contentView {

    [self showLeftView:NO];
}


// MARK: DZMReadMenuDelegate

/// 菜单将要显示
- (void)readMenuWillDisplay:(CLReadMenu *)readMenu {

    // 检查当前内容是否包含书签
    [readMenu.topView checkForMark];

    // 刷新阅读进度
    [readMenu.bottomView.progressView reloadProgress];
}

/// 点击返回
- (void)readMenuClickBack:(CLReadMenu *)readMenu {

    // 清空所有阅读缓存
    // DZMKeyedArchiver.clear()

    // 清空指定书籍缓存
    // DZMKeyedArchiver.remove(folderName: bookID)

    // 移除 DZMPageViewController，因为这个仿真模式的 UIPageViewController 不手动移除会照成内存泄漏，对象不释放
    // 它需要提前手动移除，要不然会导致释放不了走不了 deinit() 函数
    if ([CLReadConfigure sharedInstance].effectType == CLEffectTypeSimulation) {

        [self clearPageController];
    }

    // 清空坐标
    CL_READ_RECORD_CURRENT_CHAPTER_LOCATION = 0;

    // 返回
    [self.navigationController popViewControllerAnimated:YES];
}

/// 点击书签
- (void)readMenuClickMark:(CLReadMenu *)readMenu topView:(CLRMTopView *)topView markButton:(UIButton *)markButton {
    
    markButton.selected = !markButton.selected;

    if (markButton.isSelected) {
        [self.readModel insetMark:nil];
    } else {
        [self.readModel removeMarkWithRecordModel:nil];
    }

    [topView updateMarkButton];
}

/// 点击目录
- (void)readMenuClickCatalogue:(CLReadMenu *)readMenu {

    [self showLeftView:YES];

    [self.contentView showCover:YES];

    [self.readMenu showMenu:NO];
}

/// 点击日夜间
- (void)readMenuClickDayAndNight:(CLReadMenu *)readMenu {

    // 日夜间可以根据需求判断修改目录背景颜色,文字颜色等等(目前放在showLeftView方法中,leftView将要出现的时候处理)
    // leftView.updateUI()
}

/// 点击上一章
- (void)readMenuClickPreviousChapter:(CLReadMenu *)readMenu {

    if (self.readModel.recordModel.isFirstChapter) {

        NSLog(@"已经是第一章了");

    }else{

        [self goToChapter:self.readModel.recordModel.chapterModel.previousChapterID];

        // 检查当前内容是否包含书签
        [readMenu.topView checkForMark];

        // 刷新阅读进度
        [readMenu.bottomView.progressView reloadProgress];
    }
}

/// 点击下一章
- (void)readMenuClickNextChapter:(CLReadMenu *)readMenu {

    if (self.readModel.recordModel.isLastChapter) {

        NSLog(@"已经是最后一章了");

    }else{

        [self goToChapter:self.readModel.recordModel.chapterModel.nextChapterID];

        // 检查当前内容是否包含书签
        [readMenu.topView checkForMark];

        // 刷新阅读进度
        [readMenu.bottomView.progressView reloadProgress];
    }
}

/// 拖拽阅读记录
- (void)readMenuDraggingProgress:(CLReadMenu *)readMenu toPage:(NSInteger)toPage {

    if (self.readModel.recordModel.page != toPage) {

        self.readModel.recordModel.page = toPage;

        [self creatPageController:[self getCurrentReadViewController:NO]];

        // 检查当前内容是否包含书签
        [readMenu.topView checkForMark];
    }
}

/// 拖拽章节进度(总文章进度,网络文章也可以使用)
- (void)readMenuDraggingProgress:(CLReadMenu *)readMenu toChapterID:(NSString *)toChapterID toPage:(NSInteger)toPage {

    // 不是当前阅读记录章节
    if (![toChapterID isEqualToString:self.readModel.recordModel.chapterModel.chapterid]) {

        [self goToChapter:toChapterID toPage:toPage];

        // 检查当前内容是否包含书签
        [readMenu.topView checkForMark];
    }
}

/// 切换进度显示(分页 || 总进度)
- (void)readMenuClickDisplayProgress:(CLReadMenu *)readMenu {

    [self creatPageController:[self getCurrentReadViewController:NO]];
}

/// 点击切换背景颜色
- (void)readMenuClickBGColor:(CLReadMenu *)readMenu {

    // 切换背景颜色可以根据需求判断修改目录背景颜色,文字颜色等等(目前放在showLeftView方法中,leftView将要出现的时候处理)
    // leftView.updateUI()

    self.view.backgroundColor = [CLReadConfigure sharedInstance].bgColor;

    [self creatPageController:[self getCurrentReadViewController:NO]];
}

/// 点击切换字体
- (void)readMenuClickFont:(CLReadMenu *)readMenu {

    [self creatPageController:[self getCurrentReadViewController:YES]];
}

/// 点击切换字体大小
- (void)readMenuClickFontSize:(CLReadMenu *)readMenu {

    [self creatPageController:[self getCurrentReadViewController:YES]];
}

/// 点击切换间距
- (void)readMenuClickSpacing:(CLReadMenu *)readMenu {

    [self creatPageController:[self getCurrentReadViewController:YES]];
}

/// 点击切换翻页效果
- (void)readMenuClickEffect:(CLReadMenu *)readMenu {

    [self creatPageController:[self getCurrentReadViewController:NO]];
}


// MARK: 展示动画

/// 辅视图展示
- (void)showLeftView:(BOOL)isShow {
    [self showLeftView:isShow completion:nil];
}
- (void)showLeftView:(BOOL)isShow completion:(CLAnimationCompletion)completion {

    if (isShow) { // leftView 将要显示

        // 刷新UI
        [self.leftView updateUI];

        // 滚动到阅读记录
        [self.leftView.catalogView scrollRecord];

        // 允许显示
        self.leftView.hidden = NO;
    }
    [UIView animateWithDuration:CL_READ_AD_TIME delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        if (isShow) {

            self.leftView.origin = CGPointZero;

            self.contentView.origin = CGPointMake(CL_READ_LEFT_VIEW_WIDTH, 0);

        }else{

            self.leftView.origin = CGPointMake(-CL_READ_LEFT_VIEW_WIDTH, 0);

            self.contentView.origin = CGPointZero;
        }
    } completion:^(BOOL finished) {
        if (!isShow) { self.leftView.hidden = YES; }
        
        CLSafeExecuteBlock(completion);
    }];
}

- (void)dealloc {

    // 移除阅读长按视图监控
    CL_READ_NOTIFICATION_REMOVE(self);

    // 清理阅读控制器
    [self clearPageController];
    
}

- (BOOL)isHiddenNaviBar {
    return YES;
}


@end



